package com.zhangx.study.demo.mybatis.bean;

import com.zhangx.study.demo.mybatis.mapper.UserMapper;
import com.zhangx.study.demo.mybatis.service.A;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName MyFactoryBean
 * @Description TODO
 * @Author zhangx
 * @Date 2021/5/18 9:07
 **/
//@Component
public class MyFactoryBean implements FactoryBean {

    private Class mapperClass;

    public MyFactoryBean(Class mapperClass){
        this.mapperClass = mapperClass;
    }

    @Override
    public Object getObject() throws Exception {
//        在这里通过反射的方式，根据mybatis 的接口进行实例化
//        问题来了，每加一个mapper 都要写一个factoryBean么，显然不可能，这么干还不如直接在beanFactory里面注册
        Object o = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                method.invoke(proxy,args);
                return null;
            }
        });
        return o;
    }

    @Override
    public Class<?> getObjectType() {
        return mapperClass;
    }
}
